import os
from http.server import SimpleHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse, unquote
import urllib
from http import HTTPStatus

BOOK_SITE = os.path.abspath('./book/_site')
DOCS_SITE = os.path.abspath('./analysis/.lake/build/doc')

class CustomHTTPRequestHandler(SimpleHTTPRequestHandler):
    # Avoid spurious error messages from /favicon.ico
    def do_GET(self):
        if self.path == '/favicon.ico':
            self.send_response(204)
            self.end_headers()
            return
        elif self.path == '/':
            self.send_response(301)
            self.send_header('Location', '/analysis/')
            self.end_headers()
            return

        super().do_GET()


    def translate_path(self, path):
        # Prevent query strings from being treated as file paths
        parsed = urlparse(path)
        path = parsed.path
        path = unquote(path)

        # Serve /analysis-book/docs/* from DOCS_SITE
        if path.startswith('/analysis/docs/'):
            # HACK: double-slashes are being generated by JS
            path = path.replace('//', '/')
            rel_path = path[len('/analysis/docs/'):]
            return os.path.join(DOCS_SITE, rel_path)
        # Serve /analysis-book/* from BOOK_SITE
        elif path.startswith('/analysis/'):
            rel_path = path[len('/analysis/'):]
            return os.path.join(BOOK_SITE, rel_path)
        # Otherwise, serve nothing (could return a non-existent path)
        else:
            raise FileNotFoundError(f"File not found: {path}")


if __name__ == '__main__':
    import argparse
    import contextlib

    parser = argparse.ArgumentParser()
    parser.add_argument('port', default=8000, type=int, nargs='?',
                        help='bind to this port '
                             '(default: %(default)s)')
    args = parser.parse_args()

    PORT = args.port
    handler = CustomHTTPRequestHandler
    with HTTPServer(("", PORT), handler) as httpd:
        print(f"Serving at http://localhost:{PORT}/analysis/")
        print(f"/analysis: {BOOK_SITE}")
        print(f"/analysis/docs: {DOCS_SITE}")
        httpd.serve_forever()
